<template>
  <div class="visitor-container">
    <div class="flex-row justify-between">
      <!-- search -->
      <div class="searchBox">
        <el-form inline :model="queryInfo" class="demo-form-inline" label-position="left" label-width="80px">
          <el-form-item label="选择车间">
            <el-select v-model="workshopId" @change="getWorkInfo">
              <el-option
              v-for="item in workshoplist"
              :key="item.id"
              :label="item.name"
              :value="item.id">
              </el-option>
            </el-select>
          </el-form-item>
        </el-form>
      </div>
    </div>
    <div class="workmap w-100P justify-between">
      <div class="workmap-left h-100P" v-loading="showInfoLoad">
        <div class="workmap-tit">
          <h3>车间信息</h3>
          <el-button type="danger"  v-if="imgsrc" :class="{isgray: shotOn}" class="addDivBtn" @click="showArea">添加划分区域</el-button>
        </div>
        <el-row >
          <el-col :span="6" :offset="1">车间名称</el-col>
          <el-col :span="16" class="text-right" v-if="workShopinfo.name">{{ workShopinfo.name }}</el-col>
          <el-col :span="16" class="text-right" v-else> 暂无 </el-col>
        </el-row>
        <el-row>
          <el-col :span="6" :offset="1">车间编号</el-col>
          <el-col :span="16"  class="text-right"  v-if="workShopinfo.numbering">{{ workShopinfo.numbering }}</el-col>
          <el-col :span="16" class="text-right" v-else> 暂无 </el-col>
        </el-row>
        <el-row>
          <el-col :span="6" :offset="1">车间创建时间</el-col>
          <el-col :span="16"  class="text-right"  v-if="workShopinfo.createTime">{{ workShopinfo.createTime | dateTimeFormatter }}</el-col>
          <el-col :span="16" class="text-right" v-else> 暂无 </el-col>
        </el-row>
      </div>
      <div class="workmap-right h-100P"  v-loading="showInfoLoad">
        <div class="imgWrap" v-if="imgsrc"  @mousedown="mousedown($event)"  @mouseup='mouseup($event)'>
          <img  :src="imgsrc" ref="imgPosition" id="targetIMG"   />
          <div class="sonArea areabox" 
          :key="son.id" v-for="son in sonAreaList" 
          :style="{left: son.stateLefTx+'%',top: son.stateLefTy+'%',height: (son.overRighTy - son.stateLefTy)+'%',width: (son.overRighTx - son.stateLefTx)+'%'}">
            <span>{{ son.name }}</span>
            <span>
              <el-button type="success" round @click="editShot(son.id)"  icon="el-icon-edit"></el-button>
              <el-button type="danger" @click="delShot(son.id)"  icon="el-icon-delete" round></el-button>
            </span>
          </div>
          <div class="shotArea" :class="{none: !shotOn}" ref="shotArea"></div>
        </div>
        <h3 v-else style="">暂无对应图片</h3>
      </div>
    </div>
    <!-- 添加或修改 -->
    <el-dialog :title="dialogtit" :visible.sync="dialogFormVisible" width="30%" :show-close="false">
      <el-form ref="pushData" :model="pushData" :rules="rules" class="addForm">
        <el-form-item label="区域名称"  prop="name">
          <el-input  v-model="pushData.name" style="width: 250px;" />
        </el-form-item>
        <el-form-item label="坐标说明:" style="margin-bottom:0" >
          <span style="color: #f20">坐标按百分比做定位</span>
        </el-form-item>
        <el-form-item label="开始坐标X"  prop="stateLefTx">
          <el-input  v-model="pushData.stateLefTx" style="width: 250px;" />
        </el-form-item>
        <el-form-item label="开始坐标Y"  prop="stateLefTy">
          <el-input  v-model="pushData.stateLefTy" style="width: 250px;" />
        </el-form-item>
        <el-form-item label="结束坐标X"  prop="overRighTx">
          <el-input  v-model="pushData.overRighTx" style="width: 250px;" />
        </el-form-item>
        <el-form-item label="结束坐标Y"  prop="overRighTy">
          <el-input  v-model="pushData.overRighTy" style="width: 250px;" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submit('pushData')">提交</el-button>
        <el-button type="primary" @click="resetSumbit">取消</el-button>
      </div>
    </el-dialog>
    <!-- 删除车间 -->
  </div>
</template>

<script>
import {
  findmapPositioningIdByMapId,
  findWorkshopArchivesPageByParam,
  addmapPositioningId,
  updatemapPositioningId,
  findMapByWorkShopId,
  delmapPositioningIdById,
  findmapPositioningIdById
  } from '@/child-business/api/IndustrialVision' 
import { handleImage } from '@/utils/tools'
export default {
  data() {
    return {
      sonAreaList: [],
      imgHeight: 0,
      imgWidth: 0,
      shotOn: false, // 划分区域的开关
      StartLeft: 0,
      StartTop: 0,
      stateLefTy: 0,
      shotWidth: 0,
      shotHeight: 0,
      dialogtit: '添加对应区域',
      dialogFormVisible: false,
      showInfoLoad: false,
      paging: {
        pageNo: 1,
        pageSize: 12
      },
      imgsrc: undefined,
      workshopId: '', // 对应的车间ID
      queryInfo: {
        name: '',
        numbering: '',
      },
      workshoplist: [],
      pushData: {
        name: '',
        mapId: '',
        stateLefTx: 0,
        stateLefTy: 0,
        overRighTx: 0,
        overRighTy: 0,
        id: null
      },
      workShopinfo: {},
      rules: {
        name: [{ required: true, message: '请输入活动名称', trigger: 'blur' }]
      },
      typeList: []
    }
  },
  created() {
    this.getList()
  },
  filters: {
    imageFormat(value) { // 返回图片地址
      return handleImage(value)
    },
  },
  mounted() {
  },
  methods: {
    // 删除对应区域
    delShot(id){
      this.$confirm('确定删除当前区域？', '提示', {
        confirmButtonText: '确定', cancelButtonText: '取消'
      }).then(() => {
        delmapPositioningIdById({ mapPositioningId: id }).then(response => {
          if(response){
            this.getShotAreaList(this.pushData.mapId)
          }else{
            this.$message({ message: '删除失败！', type: 'error' })    
          }
        })
      }).catch(() => {   
      })
    },
    // 编辑对应区域
    editShot(id){
      // console.log(id)
      findmapPositioningIdById({ mapPositioningId: id }).then(response => {
        this.dialogFormVisible = true
        console.log(response)
        this.pushData = response
      })
    },
    // 取消提交
    resetSumbit(){
      this.dialogFormVisible = false
      this.resetShot()
    },
    // 获取所有的区域列表
    getShotAreaList(Id){
      this.showInfoLoad = true
      this.sonAreaList = []
      findmapPositioningIdByMapId({mapId: Id}).then(response => {
        this.sonAreaList = response
        this.showInfoLoad = false
      })
    },
    // 提交添加产品信息
    submit(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          if (this.pushData.id != null) {
            updatemapPositioningId(this.pushData).then(response => {
              if (response) {
                this.dialogFormVisible = false
                this.$message({ message: '修改成功！', type: 'success' })                
              }else{
                this.$message({ message: '修改失败！', type: 'error' })       
              }
              this.getShotAreaList(this.pushData.mapId)
            })
          } else {
            delete this.pushData.id
            addmapPositioningId(this.pushData).then(response => {
              if (response) {
                this.dialogFormVisible = false
                this.$message({ message: '消息添加成功！', type: 'success' })
                this.getShotAreaList(this.pushData.mapId)
              }
            })
          }
        } else {
          return false
        }
      })
    },
    // 重置shot
    resetShot(){
      const shotArea = this.$refs['shotArea']
      shotArea.style.width = '0px' 
      shotArea.style.height = '0px'
      this.pushData = {
        name: '',
        mapId: '',
        stateLefTx: 0,
        stateLefTy: 0,
        overRighTx: 0,
        overRighTy: 0,
        id: null
      }
    },
    // 操作提交
    showArea(){
      this.shotOn = true
      const shotArea = this.$refs['shotArea']
      shotArea.style.height = '0px' 
      shotArea.style.width = '0px' 
      this.$message({ message: '点击图片，划分对应区域', type: 'warning' })
    },
    // 点击图片，开始划分区域，做开关触发
    async mousedown(event) {
      const targetIMG = document.getElementById('targetIMG')
      targetIMG.src = targetIMG.getAttribute('src')
      const that = this
      targetIMG.onload = function(){
        that.imgWidth = targetIMG.width
        that.imgHeight = targetIMG.height
      }
      if(this.shotOn){
        const shotArea = this.$refs['shotArea']
        this.StartLeft = event.layerX
        this.StartTop = event.layerY
        shotArea.style.left = event.layerX + 'px' 
        shotArea.style.top = event.layerY + 'px' 
        if (event.preventDefault) {
          event.preventDefault()
        } else{
          event.returnValue = false
        }
        document.onmousemove = function (ev) {
          console.log(ev.layerX, ev.layerY)
          if (event.clientY < 0 || event.clientX < 0) {
            return false
          }
          // 宽高
          this.shotHeight = ev.layerY - event.layerY
          this.shotWidth = ev.layerX - event.layerX
          shotArea.style.height = this.shotHeight + 'px' 
          shotArea.style.width = this.shotWidth + 'px' 
        }
      }
    },
    rePercent(floatNum){
      floatNum = floatNum * 100
      const reStr = floatNum + ''
      return reStr.substring(0, reStr.indexOf('.') + 3)
    },
    // 鼠标键抬起，结束划分区域，做开关触发
    mouseup(event) {
      document.onmousemove = null
      if(this.shotOn) {
        this.$confirm('确定使用当前划分区域？', '提示', {
          confirmButtonText: '确定', cancelButtonText: '取消重画'
        }).then(() => {
          this.shotOn = false
          this.pushData.name = ''
          this.pushData.stateLefTx = this.rePercent(this.StartLeft / this.imgWidth)
          this.pushData.stateLefTy = this.rePercent(this.StartTop / this.imgHeight)
          this.pushData.overRighTx = this.rePercent(event.layerX / this.imgWidth)
          this.pushData.overRighTy = this.rePercent(event.layerY / this.imgHeight)
          this.dialogFormVisible = true
          this.shotOn = false // 关闭触发开关
        }).catch(() => {
          this.resetShot()
          this.shotOn = true // 开启触发开关      
        })
      }
    },
    // 获取当前的车间编号信息
    getWorkInfo(val) {
      this.showInfoLoad = true
      findMapByWorkShopId({ workShopId: val }).then(response => {
        console.log(response)
        this.workShopinfo = response.WorkShop
        this.imgsrc = ''
        if(response.Map && response.Map.workshopImgId){
          this.getShotAreaList(response.Map.workshopImgId)
          this.pushData.mapId = response.Map.workshopImgId
          this.imgsrc = handleImage(response.Map.workshopImgId)
        }
        this.showInfoLoad = false
      })
    },
    // 获取产品列表
    getList() {
      findWorkshopArchivesPageByParam({ workshopArchivesVO: this.queryInfo, pageNo: 1, pageSize: 10000 }).then(response => {
        this.workshoplist = response.records
      })
    },
  }
}
</script>
<style lang="scss" scoped>
 @import '@/child-business/styles/IndustrialVision.scss';
 .workmap{
   border: 1px solid #dedede;
   border-radius: 4px;;
   height: vh(860px);
   overflow: hidden;
   color: #666;
   font-size: 14px;
   .workmap-left{
     width: 25%;
     padding: 10px 15px;
     border-right: 1px solid #dedede;
     box-sizing: border-box ;
     line-height: 30px;
   }
   .workmap-right{
     width: 74%;
     padding: 10px;
     text-align: center;
     .imgWrap{
       position: relative;
       background: cadetblue;
      img{
        width: 100%;
      }
     }
   }
 }
 #imgPosition{
   position: relative;
 }
 .workmap-tit{ position: relative;}
  .addDivBtn{
    position: absolute;
    right: 10px; top: 0;
  }
  .isgray{ background: #aaa; border-color:#aaa}
  .shotArea{
    left: 0; top: 0; 
    z-index: 1; height: 1px; 
    width: 1px; opacity: 0.9; 
    background: #08184A; border-radius: 4px; 
    border: 1px solid #fff;color: #fff; 
    position: absolute;}
  .sonArea{     
    font-size: 18px; font-weight: 700; letter-spacing: 2px; border-radius: 4px;  opacity: 0.8; display: flex; justify-content: space-between;
    flex-flow:column;
    padding: 1%;
    background: #08184A; border-radius: 4px; border: 1px solid #fff;color: #fff; position: absolute;
    .el-button.is-round{padding: 5px 10px;}
  }
  .none{display: none;}
</style>
